#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <string>
#include <vector>
#include "pthread.hpp"
using namespace std;
using namespace Thread;

#define num 4
int tickets = 1000;


class ThreadData
{
public:
    ThreadData(int& tickets,string name)
    :_tickets(tickets)
    ,_name(name)
    ,_total(0)
    {}
    ~ThreadData()
    {}

public:
    int& _tickets;
    string _name;
    int _total;

};
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* threadrun(ThreadData* t)
{
    while(1)
    {
        pthread_mutex_lock(&mutex);
        if(t->_tickets > 0)
        { 
            usleep(100);
            t->_tickets--;
            pthread_mutex_unlock(&mutex);
            t->_total++;
            cout << "抢到票了: " << t->_name << "tickets-> " << t->_tickets <<endl;
        }
        else
        {
            pthread_mutex_unlock(&mutex);
            break;
        }
    }
    return nullptr;
}

int main()
{
    vector<thread<ThreadData*>> threads;
    vector<ThreadData*> data;
    for(int i = 0;i<num;i++)
    {
        string name = "thread-" + to_string(i+1);
        ThreadData* t = new ThreadData(tickets,name);
        data.push_back(t);
        threads.emplace_back(threadrun,t,name);
    }

    for(auto& thread : threads)
    {
        thread.start();
    }

    for(auto& thread : threads)
    {
        thread.join();
    }
    
    for(auto& e : data)
    {
        cout << "thread: " << e->_name << "total-> " << e->_total << endl;
    }
}